#Author: 0x9DEFA478


TargetGDBServerPort=""
TargetADBUSBSerialNumber=""
ExecPathLocal=""
ExecPathRemote=""

options=$(getopt -o a --long TargetGDBServerPort:,TargetADBUSBSerialNumber:,ExecPathLocal:,ExecPathRemote: -n $0 -- "$@")
if (( $? != 0 )); then
  exit 1
fi
eval set -- "${options}"
while true
do
  case $1 in
    --TargetGDBServerPort)
      TargetGDBServerPort=$2
      shift 2
    ;;
    --TargetADBUSBSerialNumber)
      TargetADBUSBSerialNumber=$2
      shift 2
    ;;
    --ExecPathLocal)
      ExecPathLocal=$2
      shift 2
    ;;
    --ExecPathRemote)
      ExecPathRemote=$2
      shift 2
    ;;
    --)
      shift
      break
    ;;
    *)
      echo "$0 param decode error $1"
      exit 1
    ;;
  esac
done


if [[ $TargetGDBServerPort == "" ]]; then
  echo "\e[31mTargetIP no set!\e[0m"
  exit 1
fi
if [[ $ExecPathLocal == "" ]]; then
  echo "\e[31mExecPathLocal no set!\e[0m"
  exit 1
fi
if [[ $ExecPathRemote == "" ]]; then
  echo "\e[31mExecPathRemote no set!\e[0m"
  exit 1
fi


ADBArgs=""

if [[ $TargetADBUSBSerialNumber != "" ]]; then
  ADBArgs="${ADBArgs}-s ${TargetADBUSBSerialNumber} "
fi

ADBArgArr="${ADBArgs}shell"

ExecName=$(basename $ExecPathRemote)


adb ${ADBArgArr} "killall ${ExecName}"
adb ${ADBArgArr} "ProcPID=\$(ss -tlnp | grep LISTEN | grep ${TargetGDBServerPort} | sed -n 's/.*pid=\([0-9]\+\).*/\1/p') && if [[ \$ProcPID != \"\" ]]; then echo kill \$ProcPID;kill \$ProcPID; else echo no process Port: ${TargetGDBServerPort}; fi"

adb "${ADBArgs}push" ${ExecPathLocal} ${ExecPathRemote}
if (( $? != 0 )); then
  exit 2
fi

adb ${ADBArgArr} "chmod +x ${ExecPathRemote}"
if (( $? != 0 )); then
  exit 3
fi

